﻿Imports System.Text.RegularExpressions
Imports System.ComponentModel
Imports OnlineVideos.Sites.WebSite
Imports MediaPortal.GUI.Library
Imports MediaPortal.Dialogs
Imports System.Net
Imports HtmlAgilityPack

Public Class YouTubeDocumentaries
    Inherits SiteUtilBase

    Private baseURL As String = "http://www.youtubedocumentaries.com"

    Public Overrides Function DiscoverDynamicCategories() As Integer
        Dim webData = GetWebData(TVALaCartaUtil.CombinePath(baseURL, "browse_ajax.cfm"))

        If Settings.Categories Is Nothing Then Settings.Categories = New BindingList(Of Category)

        Dim m = Regex.Match(webData, "<tr>\s*<td>\s*<a\shref=""(?<url>[^""]*)"">(?<title>[^<]*)</a>\s*</td>\s*<td\salign=""right"">(?<count>[^<]*)</td>\s*</tr>")
        While m.Success
            Dim newCat = New RssLink()
            newCat.Name = Web.HttpUtility.HtmlDecode(m.Groups("title").Value)
            newCat.Url = TVALaCartaUtil.CombinePath(baseURL, m.Groups("url").Value)
            newCat.EstimatedVideoCount = m.Groups("count").Value
            newCat.HasSubCategories = True

            Settings.Categories.Add(newCat)

            m = m.NextMatch()
        End While

        Settings.DynamicCategoriesDiscovered = (Settings.Categories.Count > 0)

        Return Settings.Categories.Count
    End Function

    Public Overrides Function DiscoverSubCategories(parentCategory As Category) As Integer
        Dim webData = GetWebData(CType(parentCategory, RssLink).Url)
        Dim regExp = "onload=""xmlhttpPost\('browse_ajax\.cfm\?tagID=(?<id>[^']*)'\);"""
        Dim m = Regex.Match(webData, regExp)
        If Not m.Success Then Return 0

        webData = GetWebData(TVALaCartaUtil.CombinePath(baseURL, "browse_ajax.cfm?tagID=" + m.Groups("id").Value))

        Dim htmlDoc As New HtmlDocument()
        htmlDoc.LoadHtml(webData)
        Dim titlesAndUrls = htmlDoc.DocumentNode.SelectNodes("//strong[./a/@href[contains(., 'documentary.cfm')]]")
        Dim datesAndParts = htmlDoc.DocumentNode.SelectNodes("//table[@style='width: 100%; padding-right:12px;']/tr/td[contains(., '- [')]")
        Dim thumbs = htmlDoc.DocumentNode.SelectNodes("//a/img[@alt='Watch now']")
        Dim descriptions = htmlDoc.DocumentNode.SelectNodes("//div[@style='margin-top: 5px;']")

        parentCategory.SubCategories = New List(Of Category)

        If titlesAndUrls Is Nothing OrElse titlesAndUrls.Count = 0 Then Return 0

        Dim getParts = Function(text As String)
                           Dim value As Integer = 0
                           If text.Contains("- [") Then
                               text = text.Trim()
                               Dim number As String = ""
                               For i As Integer = text.LastIndexOf("[") + 1 To text.LastIndexOf("]") - 1
                                   If Char.IsLetter(text(i)) Then Exit For
                                   number += text(i)
                               Next

                               Integer.TryParse(number, value)
                           End If

                           Return value
                       End Function

        For i As Integer = 0 To titlesAndUrls.Count - 1
            Dim newCat = New RssLink()
            newCat.Name = titlesAndUrls(i).InnerText.Trim()
            newCat.Url = TVALaCartaUtil.CombinePath(baseURL, titlesAndUrls(i).SelectSingleNode("a").GetAttributeValue("href", ""))
            newCat.ThumbnailImage = thumbs(i).GetAttributeValue("src", "")
            newCat.Description = descriptions(i).InnerText.Trim()
            newCat.EstimatedVideoCount = getParts(datesAndParts(i).InnerText)
            newCat.ParentCategory = parentCategory

            parentCategory.SubCategories.Add(newCat)
        Next

        Return parentCategory.SubCategories.Count
    End Function

    Public Overrides Function getVideoList(category As Category) As System.Collections.Generic.List(Of VideoInfo)
        Dim rssLink = CType(category, RssLink)
        Dim webData = GetWebData(rssLink.Url)
        Dim regExp = "<embed\ssrc=""(?<url>[^""]*)"""
        Dim m = Regex.Match(webData, regExp)

        Dim videos As New List(Of VideoInfo)
        Dim part As Integer = 1
        While m.Success
            Dim newVideo = New VideoInfo()
            newVideo.Title = "Part " + part.ToString()
            newVideo.VideoUrl = m.Groups("url").Value
            newVideo.Description = newVideo.Title + Environment.NewLine + rssLink.Description

            videos.Add(newVideo)

            m = m.NextMatch()
            part += 1
        End While

        Return videos
    End Function

    Public Overrides Function getUrl(video As VideoInfo) As String
        'Dim webData As String = GetWebData(TVALaCartaUtil.CombinePath(baseURL, video.VideoUrl))
        'Dim regExp = "<embed\ssrc=""(?<VideoUrl>[^""]*)""\stype=""application/x-shockwave-flash""\sallowscriptaccess=""always""\sallowfullscreen=""true""\swidth=""100%""></embed>"
        'Dim m = Regex.Match(webData, regExp)
        'Return m.Groups("VideoUrl").Value + "&autoplay=1&hd=1&showinfo=0&showsearch=0"

        ' TODO: How the hell do you parse the URL so that MediaPortal plays the video without the player's UI???
        ' Tried to "understand" the YoutTube.cs (http://code.google.com/p/mp-onlinevideos2/source/browse/#svn%2Ftrunk%2FSiteUtilProjects%2FOnlineVideos.Sites.offbyone%2FGoogle%2FGData%2FYouTube) and YoutTubeUtil.cs (http://code.google.com/p/mp-onlinevideos2/source/browse/trunk/SiteUtilProjects/OnlineVideos.Sites.offbyone/YouTubeUtil.cs) from offbyone but it is way too complicated.
        ' There has to be an easier/simpler way!
        Return video.VideoUrl + "&autoplay=1&hd=1&showinfo=0&showsearch=0"
    End Function
End Class
